import {ElMessage} from 'element-plus'
import {copy as CopyUnit} from "@/units/system";

/**
 * 复制指令
 */
const copy: { name: string, directive: any } = {
    name: 'copy',
    directive: {
        mounted(el: any, binding: any) {
            el.cpval=(binding.value ? binding.value : el.innerHTML).toString()
            el.style.cursor = 'pointer'
            el.copyHandle = function () {
                CopyUnit(el.cpval).then(res => {
                    if (res) {
                        ElMessage({showClose: true, message: '已复制到粘贴板', type: 'success', center: true})
                    } else {
                        ElMessage({showClose: true, message: '复制失败,请手动复制', type: 'error'})
                    }
                })
            }
            el.addEventListener('click', el.copyHandle);
        },
        beforeUpdate(el: any, binding: any) {
            el.cpval = binding.value ? binding.value : el.innerHTML;
        },
        beforeUnmount(el: any) {
            el.removeEventListener('click', el.copyHandle, false); //监听按钮点击事件
        }
    }
}

/**
 * 复制指令
 */
export default copy